package StudyCode.summary.csv;

import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CSVRecordParser {
	private static List<String> parseCsvRecord(String record,
	                                           char csvSeparator) {
		boolean quoted = false;
		StringBuilder fieldBuilder = new StringBuilder();
		List<String> fields = new ArrayList<String>();

		for (int i = 0; i < record.length(); i++) {
			char c = record.charAt(i);
			fieldBuilder.append(c);

			if (c == '"') {
				quoted = !quoted;
			}

			if ((!quoted && c == csvSeparator)
					|| i + 1 == record.length()) {
				String field = fieldBuilder.toString()
						.replaceAll(csvSeparator + "$", "")
						.replaceAll("^\"|\"$", "")
						.replace("\"\"", "\"");
				fields.add(field.trim());
				fieldBuilder = new StringBuilder();
			}
		}

		return fields;
	}
}
